package com.csf.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
@Aspect
public class ServiceAspect {
//    引入日志
     private static final Logger logger = LoggerFactory.getLogger(ServiceAspect.class);
//需要插入到哪些方法上
     @Pointcut("execution(* com.csf.service.impl.*.*(..))")
     public void pointCut(){
     }
//     在插入的方法上需要做哪些操作（Advice）
    @Before("pointCut()")
     public void BeforeMethod(JoinPoint joinPoint){
//         需要日志打印出：什么IP地址在什么时间访问了那个资源
//        首先得到IP地址，通过工具RequestContextHolder得到
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        if (servletRequestAttributes== null){
            return;
        }
        HttpServletRequest request = servletRequestAttributes.getRequest();

        String ip = request.getRemoteHost();
//        然后得到得到访问时间
        String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
//        最后得到访问的资源
        String tarSource = joinPoint.getSignature().getDeclaringTypeName()+"."+joinPoint.getSignature().getName();
        logger.info("用户ip为:"+ip+"在"+time+"访问了"+tarSource);
     }
}
